<template>
  <div>
    <jxf-titletip :title="title" :hasGoBack="true" :hasRefresh="false" @goBack="$emit('goBack')"></jxf-titletip>
    <div class="jxf-content mt20">
      <el-card class="jxf-table-card mt10">
        <div slot="header" class="clearfix">
          <span>{{title}}</span>
        </div>
        <div class="listArea">
          <el-form :model="cityManngeInfo" ref="cityManngeInfo" :rules="rules">
            <el-form-item label="方案名称:" prop="accountName" required>
              <el-input v-model="cityManngeInfo.accountName" maxlength="25" clearable :disabled="dataInfo.pageType === '1'"></el-input>
            </el-form-item>
            <el-form-item label="城市选择：" prop="cityId" required>
              <AreaInput :searchInfo.sync="cityManngeInfo" :isDisable="dataInfo.pageType === '1'"></AreaInput>
            </el-form-item>
            <el-form-item label="星级对应账期设置:" required>
              <el-table :data="tableData3" class="setting" style="width: 561px" border>
                <el-table-column label="充值金额区间" width="374" align="center">
                  <el-table-column label="充值金额 至 充值金额" align="center">
                    <template slot-scope="scope">
                      <el-row :gutter="10">
                        <el-col :span="10">
                          <el-input v-model="scope.row.min" maxlength="9" @keyup.native="numberMinChange($event)" :disabled="dataInfo.pageType  === '1'"></el-input>
                        </el-col>
                        <el-col :span="2" style="text-align: center;line-height: 40px">至</el-col>
                        <el-col :span="10">
                          <el-input v-model="scope.row.max" maxlength="9" :disabled="!scope.row.min && dataInfo.pageType !== '1' || dataInfo.pageType  === '1'" @keyup.native="numberMaxChange($event)"></el-input>
                        </el-col>
                      </el-row>
                    </template>
                  </el-table-column>
                </el-table-column>
                <el-table-column label="返利" width="186" align="center">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.rate" :disabled="dataInfo.pageType === '1'">
                      <template slot="append">%</template>
                    </el-input>
                    <div>
                      <i class="c-red" v-if="scope.row.numWrong === 1">请输入两位小数以内的正数</i>
                      <i class="c-red" v-if="scope.row.numWrong === 2">费率不能大于100</i>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              <i class="el-icon-plus addPeriod" @click="addPeriod" v-if="dataInfo.pageType  !== '1'"></i>
            </el-form-item>
            <el-form-item label="备注说明:">
              <el-input
                v-model="cityManngeInfo.remark"
                autocomplete="off"
                type="textarea"
                maxlength="150"
                :autosize="{ minRows: 4, maxRows: 6}"
                placeholder="备注" :disabled="dataInfo.pageType === '1'"></el-input>
              <p class="textAreaMsg">({{cityManngeInfo.remark ? cityManngeInfo.remark.length : 0}}/150)</p>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm" v-if="dataInfo.pageType !== '1'">确认</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
  export default {
    name: "AddRebate",
    props: {
      dataInfo: {
        type: Object,
        default: () => {}
      },
      title: {
        type: String,
        default: "添加返利方案"
      }
    },
    data() {
      return {
        cityManngeInfo: {
          provinceId: this.dataInfo.provinceId,
          cityId: this.dataInfo.cityId,
          accountName: this.dataInfo.schemeName,
          remark: this.dataInfo.remark
        },
        count: 0,
        rules: {
          accountName: [
            { required: true, message: '方案名称不能为空', trigger: ['blur', 'change'] },
          ],
          cityId: [
            { required: true, message: '城市选择不能为空', trigger: ['blur', 'change'] },
          ],
          remark: [
            { required: true, message: '备注不能为空', trigger: ['blur', 'change'] },
            { min: 1, max: 150, message: '长度不能超过150个字', trigger: ['blur', 'change'] }
          ]
        },
        tableData3: this.dataInfo && this.dataInfo.itemList ? this.dataInfo.itemList : []
      }
    },
    methods: {
      handleClose(done) {
        this.count = 0;
        this.resetForm()
        done()
      },
      resetForm() {
        this.count = 0;
        this.tableData3 = []
        this.$refs['cityManngeInfo'].resetFields()
      },
      numberMinChange(e) {
        let reg = /^\d{0,8}\.{0,1}(\d{1,2})?$/;
        if(e.target.value && !reg.test(e.target.value)) {
          e.target.value = e.target.value.substring(0, e.target.value.length - 1)
        }
        if(e.target.value && reg.test(e.target.value) && e.target.value > 999999999) {
          e.target.value = e.target.value.substring(0, e.target.value.length - 1)
        }
      },
      numberMaxChange(e) {
        let reg = /^\d{0,8}\.{0,1}(\d{1,2})?$/;
        if(e.target.value && !reg.test(e.target.value)) {
          e.target.value = e.target.value.substring(0, e.target.value.length - 1)
        }
        if(e.target.value && reg.test(e.target.value) && e.target.value > 999999999) {
          e.target.value = e.target.value.substring(0, e.target.value.length - 1)
        }
      },
      // 加账期
      addPeriod() {
        ++this.count;
        this.tableData3.push({
          min: "",
          max: "",
          rate: "",
          numWrong: 0
        });

      },
      submitForm() {
        this.$refs['cityManngeInfo'].validate((valid) => {
          if(valid) {
            if(this.tableData3.length == 0) {
              this.$notify({
                title: '警告',
                message: '账期与费率设置不能为空',
                type: 'warning'
              });
              return false
            }
            // 判断返利是否有空值
            let isNull = false
            // 数组对象深拷贝
            let tableInfo = this.tableData3.map(item =>{
              return {...item}
            })
            tableInfo.forEach(item => {
              if(item.rate !== "" && (item.numWrong === undefined || item.numWrong === 0)) {
                if(item.rate != "0") {
                  item.rate = Math.round(item.rate * 100) / 10000
                }
              } else {
                isNull = true;
              }
              // item.starName = item.starName.substring(3, item.starName.length)
            })
            if(isNull) {
              return false;
            }
            let data = {}
            let cityData = {
              type: 2,
              id: this.cityManngeInfo.provinceId
            }
          ajax.post(apis.common.getCityList, cityData).then(res => {
            if(res.code == "10000000") {
              res.data.map((item, index) => {
                if(item.id == this.cityManngeInfo.cityId) {
                  if(this.dataInfo && this.dataInfo.id) {
                    data = {
                      cityId: this.cityManngeInfo.cityId,
                      schemeName: this.cityManngeInfo.accountName,
                      remark: this.cityManngeInfo.remark,
                      itemList: tableInfo,
                      id: this.dataInfo ? this.dataInfo.id : "",
                      cityName: item.name
                    }
                    ajax.post(apis.finance.updateRebate, data).then(res => {
                      if(res.code === "10000000") {
                        this.$message({
                          type: 'success',
                          message: '更新成功'
                        });
                        this.resetForm()
                        this.$emit('fresh')
                        this.$emit('goBack')
                      } else {
                        this.tableData3.map((item, index) => {
                          if(item.numWrong === 0) {
                            item.rate = item.rate ? Math.round(item.rate * 100) : 0
                          }
                        })
                        this.$message.error(res.message)
                      }
                    })
                  } else {
                    data = {
                      cityId: this.cityManngeInfo.cityId,
                      schemeName: this.cityManngeInfo.accountName,
                      remark: this.cityManngeInfo.remark,
                      itemList: tableInfo,
                      id: "",
                      cityName: item.name
                    }
                    ajax.post(apis.finance.addRebate, data).then(res => {
                      if(res.code === "10000000") {
                        this.$message({
                          type: 'success',
                          message: '新增成功'
                        });
                        this.resetForm()
                        this.$emit('fresh')
                        this.$emit('goBack')
                      } else {

                        this.tableData3.map((item, index) => {
                          if(item.numWrong === 0) {
                            item.rate = item.rate ? Math.round(item.rate * 100) : 0
                          }
                        })

                        this.$message.error(res.message)
                      }
                    })
                  }
                }
              })
            }
          })
          .catch(err => {});
          }
        })


      },
    },
    watch: {
      tableData3: {
        handler(curVal,oldVal){
          let reg = /^\d+(\.\d{0,2})?$/
          this.tableData3.map((item, index) => {
            if(reg.test(item.rate)) {
              if(parseInt(item.rate) > 100) {
                item.numWrong = 2;
              } else {
                item.numWrong = 0;
              }
            } else {
              item.numWrong = 1
            }
          })

        },
        deep:true
      }
    }
  }
</script>

<style lang="scss" scoped>
  .el-col-11 {
    width: auto;
  }

  .el-form {
    max-width: 900px;
    min-width: 500px;
    .el-input {
      width: 300px;

    }
    .textAreaMsg {
      width: 100%;
      text-align: right;
    }
    .addPeriod {
      cursor: pointer;
    }
    .setting {
      .el-input {
        width: 80%;

      }
    }
  }
</style>
